class Solution28 {
    public int ret;
    public int count;
    public int uniquePathsIII(int[][] grid) {
        int x = 0;
        int y = 0;
        for(int i = 0; i < grid.length; i++) {
            for(int j = 0; j < grid[0].length; j++) {
                if(grid[i][j] == 0) count++;
                if(grid[i][j] == 1) {
                    x = i;
                    y = j;
                }
            }
        }
        dfs(grid,x,y,0);
        return ret;
    }

    int[] dx = {1,-1,0,0};
    int[] dy = {0,0,1,-1};
    public void dfs(int[][] grid, int x, int y, int step) {
        for(int k = 0; k < 4; k++) {
            int x1 = x + dx[k];
            int y1 = y + dy[k];
            if(x1 >= 0 && x1 < grid.length && y1 >= 0 && y1 < grid[0].length && grid[x1][y1] == 2 && step == count) {
                ret++;
                return;
            }
            if(x1 >= 0 && x1 < grid.length && y1 >= 0 && y1 < grid[0].length && grid[x1][y1] == 0) {
                grid[x1][y1] = -1;
                dfs(grid,x1,y1,step+1);
                grid[x1][y1] = 0;
            }
            
        }

    }
}